package com.studerb.view.tasks.active;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.studerb.tasks.interfaces.ITask;

public class ActiveTasksTable extends JTable {
	class ActiveTasksListSelectionEL implements ListSelectionListener {

		@Override public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting()) {
				return;
			}
			int selectedRowIndex = getSelectedRow();
			if (selectedRowIndex != -1) {
				int convertedIndex = convertRowIndexToModel(selectedRowIndex);
				ITask task = activeTasksTableModel.getTask(convertedIndex);
				selectedTask = task;
				logger.debug("Set selected task to : " + task.getTitle());
			}
		}
	}

	class ActiveTasksMouseListener extends MouseAdapter {

		@Override public void mouseClicked(MouseEvent e) {
			if (SwingUtilities.isRightMouseButton(e)) {
				JTable table = (JTable) e.getSource();
				int row = table.rowAtPoint(e.getPoint());
				// changeSelection(row, 0, false, false);
				logger.debug("Got right click at row: " + row);
				JPopupMenu popupMenu = new JPopupMenu();
				JMenuItem menuItemPause = new JMenuItem(PAUSE_TASK);
				JMenuItem menuItemCancel = new JMenuItem(CANCEL_TASK);
				JMenuItem menuItemMoveUp = new JMenuItem(MOVE_TASK_UP);
				JMenuItem menuItemMoveDown = new JMenuItem(MOVE_TASK_DOWN);
				popupMenu.add(menuItemPause);
				popupMenu.add(menuItemCancel);
				popupMenu.add(menuItemMoveUp);
				popupMenu.add(menuItemMoveDown);
				RightClickAL rightClickAL = new RightClickAL();
				menuItemPause.addActionListener(rightClickAL);
				menuItemCancel.addActionListener(rightClickAL);
				menuItemMoveUp.addActionListener(rightClickAL);
				menuItemMoveDown.addActionListener(rightClickAL);

				popupMenu.show(table, e.getX(), e.getY() - 10);
			}
		}
	}

	class ProgresBarCellRenderer implements TableCellRenderer {

		@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
			JProgressBar bar = progressBars.get(row);
			bar.setValue((Integer) table.getValueAt(row, ActiveTasksTableModel.Column.PROGRESS.ordinal()));
			return bar;
		}
	}

	class RightClickAL implements ActionListener {
		@Override public void actionPerformed(ActionEvent e) {
			ITask task = selectedTask;
			if (task == null) {
				return;
			}

			if (e.getActionCommand() == CANCEL_TASK) {
				logger.debug("Canceling task: " + task.toString());
				if (!task.cancel(true)) {
					logger.warn("Error cancelling Task");
					JOptionPane.showMessageDialog(null, "Error cancelling Task", "Cancelling Task Error", JOptionPane.ERROR_MESSAGE);
				}
			}
			else if (e.getActionCommand() == PAUSE_TASK) {
				logger.debug("pausing task: " + task.toString());
				if (!task.pause()) {
					logger.warn("Error PAUSING Task");
					JOptionPane.showMessageDialog(null, "Error Pausing Task", "Pausing Task Error", JOptionPane.ERROR_MESSAGE);
				}

			}
			else if (e.getActionCommand() == MOVE_TASK_UP) {
				logger.debug("moving task UP: " + task.toString());
			}
			else if (e.getActionCommand() == MOVE_TASK_DOWN) {
				logger.debug("pausing task DOWN: " + task.toString());
			}

		}

	}

	private final Logger logger = Logger.getLogger(ActiveTasksTable.class);
	private final static String CANCEL_TASK = "Cancel";

	private final static String PAUSE_TASK = "Pause";
	private final static String MOVE_TASK_UP = "Move Task Up";

	private final static String MOVE_TASK_DOWN = "Move Task Down";

	protected ITask selectedTask = null;

	@Autowired protected ActiveTasksTableModel activeTasksTableModel;

	protected List<JProgressBar> progressBars = Collections.synchronizedList(new ArrayList<JProgressBar>());

	public synchronized void addProgressBar() {
		JProgressBar pb = new JProgressBar(0, 100);
		progressBars.add(pb);
	}

	public void init() {
		// this.setAutoCreateRowSorter(true);
		setModel(activeTasksTableModel);
		// set the columnModel editor for progress bars
		this.getColumnModel().getColumn(ActiveTasksTableModel.Column.PROGRESS.ordinal()).setCellRenderer(new ProgresBarCellRenderer());
		selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		selectionModel.addListSelectionListener(new ActiveTasksListSelectionEL());
		addMouseListener(new ActiveTasksMouseListener());
	}

	public synchronized void removeProgressBar(int index) {
		progressBars.remove(index);
	}

}
